<?php

namespace app\admin\controller;

use app\admin\model\arole;
use app\admin\server\Menu;
use think\Db;
use think\Request;
use think\Session;
use think\Validate;

class Role extends AdminBase
{
    /**
     * 展示
     * @return mixed|\think\response\Json
     */
    public function index()
    {
        if (Request::instance()->isPost()) {
            try {
                $page = input('page/d', 1);
                $limit = input('limit/d', 10);
                $where = [];


                $status = input('status/d', -1);
                if ($status >= 0) $where['status'] = $status;

                $rolename = input('rolename/s');
                if (!empty($rolename)) $where['rolename'] = ['like', '%' . $rolename . '%'];

                //排序
                $order = input('order/s', 'desc');
                $field = input('field/s', 'update_time');

                $list = Db::name('arole');
                $count = Db::name('arole');

                if (!empty($where)) {
                    $count = $count->where($where);
                    $list = $list->where($where);
                }

                $list = $list->field('roleid,rolename,status,FROM_UNIXTIME(create_time,"%Y-%m-%d %H:%i:%s") as create_time,FROM_UNIXTIME(update_time,"%Y-%m-%d %H:%i:%s") as update_time')
                    ->limit(($page - 1) * $limit, $limit)
                    ->order($field, $order)
                    ->select();

                $count = $count->count();

                $json = ['code' => 0, 'msg' => 'success', 'data' => $list, 'count' => $count];
            } catch (\Exception $e) {
                $json = ['code' => -1, 'msg' => $e->getMessage()];
            }
            return json($json);
        }

        return $this->fetch();
    }

    /**
     * 添加/编辑
     * @return mixed|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function save()
    {
        if (Request::instance()->isPost()) {
            try {
                $post = input();
                $type = input('type/d', 1);

                $rule = [
                    ['roleid', 'egt:0', 'adid不合法'],
                    ['status', 'require|in:0,1', '用户密码不能超过16个字符'],
                ];
                if ($type == 1) $rule = array_merge(
                    $rule,
                    [
                        ['rolename', 'require|length:1,20', '请填写用户名|用户名不能超过20个字符'],
                    ]
                );

                $validate = new Validate($rule);
                if (!$validate->check($post)) throw new \Exception($validate->getError());

                empty($post['roleid']) ? arole::aroleAdd($post) : arole::aroleUpdate($post);

                $json = ['status' => 200, 'msg' => 'success'];
            } catch (\Exception $e) {
                $json = ['status' => 400, 'msg' => $e->getMessage()];
            }
            return json($json);
        }

        $id = input('id/d');
        $this->assign('id', $id);

        if (!empty($id)) {
            $info = Db::name('arole')->find($id);
            $this->assign('info', $info);
        }

        $type = input('type', 'add');
        $this->assign('type', $type);

        return $this->fetch();
    }

    /**
     * 删除节点
     * @return \think\response\Json
     */
    public function del()
    {
        try {
            $roleid = input('roleid/d');
            if (empty($roleid)) throw new \Exception('缺少id');

            arole::aroleDel(['roleid' => $roleid]);

            $json = ['status' => 200, 'msg' => 'success'];
        } catch (\Exception $e) {
            $json = ['status' => 400, 'msg' => $e->getMessage()];
        }
        return json($json);
    }

    /**
     * 权限
     */
    public function power()
    {
        $type = input('type/d', 1);
        if (Request::instance()->isPost()) {
            try {
                $roleid = input('roleid/d');
                if (empty($roleid)) throw new \Exception('非法链接');

                $arole = arole::get($roleid);
                if (empty($arole)) throw new \Exception('获取不到角色信息');

                $json = [
                    'status' => 200,
                    'msg' => 'success',
                    'data' => Menu::getNode(0, 1, explode(',', $arole['powerid'])),
                ];
            } catch (\Exception $e) {
                $json = ['status' => 400, 'msg' => $e->getMessage()];
            }
            return json($json);
        }

        $this->assign('type', $type);

        return $this->fetch();
    }

    public function powerSave()
    {
        if (Request::instance()->isPost()) {
            try {
                $roleid = input('roleid/d');
                if (empty($roleid)) throw new \Exception('缺少roleid');

                $power = input('powere/a');
                if (!is_array($power)) throw new \Exception('非法参数');

                $power = !empty($power) ? implode(',', $power) : '';

                arole::aroleUpdate(['roleid' => $roleid, 'powerid' => $power]);
                Menu::clear();

                //如果保存权限与当前登录角色相同,则修改session相关信息
                $user = Session::get('user', 'admin');
                if ($user['rid'] == $roleid) {
                    $user['powerid'] = $power;
                    Session::set('user', $user, 'admin');
                }

                $json = ['status' => 200, 'msg' => 'success'];
            } catch (\Exception $e) {
                $json = ['status' => 400, 'msg' => $e->getMessage()];
            }
            return json($json);
        }
    }
}